﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Net;
using System.IO;
using System.Text;
using Model;
using BLL;

public partial class Admin_WeiMenuList:BasePage
{
    Access ac = new Access();
    MerchantsBO mbo = new MerchantsBO();
    protected void Page_Load(object sender, EventArgs e)
    {
       string s= @" {
     ""button"":[
     {	
          ""type"":""click"",
          ""name"":""微首页"",
          ""key"":""V1001_TODAY_home""
      },
      {
           ""type"":""click"",
           ""name"":""微团购"",
           ""key"":""V1001_TODAY_group""
      },
      {
           ""name"":""关注我们"",
           ""sub_button"":[
            {
               ""type"":""click"",
               ""name"":""商户介绍"",
               ""key"":""V1001_HELLO_introduce""
            },
            {
               ""type"":""click"",
               ""name"":""价格"",
               ""key"":""V1001_price""
            },
            {
               ""type"":""click"",
               ""name"":""地址"",
               ""key"":""V1001_address""
            }]      
}]
}";
      
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        string Access_token = "";
        //获取access_token
        string url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+GetAppid()+"&secret="+GetSecret()+"";
        try
        {
            string token = PostRequest(url);
            if (token.Contains("7200"))
            {
                string[] b = token.Split('\"');
                Access_token = b[3];
            }
        }
        catch (Exception)
        {
            Access_token = "";
        }
        Merchants m = mbo.GetModel(CurrentUserInfo.MID);
        if (m != null)
        {
            DataTable dt = ac.GetWeiMenuByMid(CurrentUserInfo.MID);
            string d = @" {
     ""button"":[";
            List<string> list = new List<string>();
            DataRow[] rows = dt.Select("parentid=0");
            foreach (DataRow dr in rows)
            {

                if (dr["haveC"].ToString() == "haveC")
                {
                    string s = @"{
           ""name"":""{0}"",
           ""sub_button"":[";
                    s = s.Replace("{0}", dr["name"].ToString());
                    d += s;
                    DataRow[] rows2 = dt.Select("parentid=" + dr["ID"].ToString());
                    foreach (DataRow dr2 in rows2)
                    {
                        s = @"{
               ""type"":""{2}"",
               ""name"":""{0}"",
               ""{3}"":""{1}""
            },";
                        string keys = "";
                        if (dr2["type"].ToString() == "2")
                        {
                            if (dr2["keys"].ToString().Contains(GetURL()))
                                keys = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + GetAppid() + "&redirect_uri=" + dr2["keys"].ToString() + "&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
                            else
                                keys = dr2["keys"].ToString();
                        }
                        else
                            keys = dr2["keys"].ToString();
                        s = s.Replace("{0}", dr2["Name"].ToString()).Replace("{1}", keys).Replace("{2}", dr2["type"].ToString() == "2" ? "view" : "click").Replace("{3}", dr2["type"].ToString() == "2" ? "url" : "key");
                        d += s;
                    }
                    d = d.Substring(0, d.Length - 1);
                    d += "]},";
                }
                else
                {
                    string s = @"{
               ""type"":""{2}"",
               ""name"":""{0}"",
               ""{3}"":""{1}""
            },";
                    string keys = "";
                    if (dr["type"].ToString() == "2")
                    {
                        if (dr["keys"].ToString().Contains(GetURL()))
                            keys = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + GetAppid() + "&redirect_uri=" + dr["keys"].ToString() + "&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
                        else
                            keys = dr["keys"].ToString();
                    }
                    else
                        keys = dr["keys"].ToString();
                    s = s.Replace("{0}", dr["Name"].ToString()).Replace("{1}", keys).Replace("{2}", dr["type"].ToString() == "2" ? "view" : "click").Replace("{3}", dr["type"].ToString() == "2" ? "url" : "key");
                    d += s;
                }
            }
            d = d.Substring(0, d.Length - 1);
            d += "}]}";
            Response.Write(d);
            var postUrl = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + m.Access_token;
            if (Access_token != "")
                postUrl = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + Access_token;
            var resMessage = HttpXmlPostRequest(postUrl, d, Encoding.UTF8);
            Response.Write(resMessage);
            
        }
    }

    //GET方式
    public string PostRequest(string url)
    {
        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);  //定义请求对象，并设置好请求URL地址
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();    //定义响应对象，request在调用GetResponse方法事执行请求了，而不是在HttpWebRequest.Create的时候执行。
        Stream stream = response.GetResponseStream(); //定义一个流对象，来获取响应流
        StreamReader sr = new StreamReader(stream);  //定义一个流读取对象，读取响应流
        string responseHTML = sr.ReadToEnd();
        return responseHTML;
    }


    /// <summary>
    /// HttpPost发送XML并返回响应
    /// </summary>
    /// <param name="postUrl"></param>
    /// <param name="xml"></param>        
    /// <param name="encoding"></param>         
    /// <returns>Response响应</returns>
    public static string HttpXmlPostRequest(string postUrl, string postXml, Encoding encoding)
    {
        if (string.IsNullOrEmpty(postUrl))
        {
            throw new ArgumentNullException("HttpXmlPost ArgumentNullException :  postUrl IsNullOrEmpty");
        }

        if (string.IsNullOrEmpty(postXml))
        {
            throw new ArgumentNullException("HttpXmlPost ArgumentNullException : postXml IsNullOrEmpty");
        }

        var request = (HttpWebRequest)WebRequest.Create(postUrl);
        byte[] byteArray = encoding.GetBytes(postXml);
        request.ContentLength = byteArray.Length;
        request.Method = "post";
        request.ContentType = "text/xml";

        using (var requestStream = request.GetRequestStream())
        {
            requestStream.Write(byteArray, 0, byteArray.Length);
        }

        using (var responseStream = request.GetResponse().GetResponseStream())
        {
            return new StreamReader(responseStream, encoding).ReadToEnd();
        }
    }
}